package main

import (
	"bufio"
	"fmt"
	"os"
	"os/exec"
	"strings"
)

const (
	MAXGOPROCS   = 128
	WELCOME_INFO = `
欢迎使用 ScriptManager!
可用命令: 
start [脚本], 
stop [脚本], 
kill[脚本], 
list, 
exit, 
clear
help
`
	HELP_INFO = `
可用命令: 
start [脚本], 
stop [脚本], 
kill[脚本], 
list, 
exit, 
clear
help
`
)

func main() {
	sm := NewScriptManager(MAXGOPROCS)
	scanner := bufio.NewScanner(os.Stdin)

	fmt.Println(WELCOME_INFO)
	for {
		fmt.Print("> ")
		if !scanner.Scan() {
			break
		}
		line := strings.TrimSpace(scanner.Text())
		if line == "" {
			continue
		}
		args := strings.Fields(line)
		switch args[0] {
		case "start":
			if len(args) < 2 {
				fmt.Println("用法: start [脚本名]")
				continue
			}
			for _, script := range args[1:] {
				sm.RunScript(script)
			}
		case "stop":
			if len(args) < 2 {
				fmt.Println("用法: stop [脚本名]")
				continue
			}
			for _, script := range args[1:] {
				sm.StopScript(script)
			}
		case "kill":
			if len(args) < 2 {
				fmt.Println("用法: kill [脚本名]")
				continue
			}
			for _, script := range args[1:] {
				sm.KillScript(script)
			}
		case "list":
			scripts := sm.ListScripts()
			fmt.Println("正在运行的脚本:")
			for _, script := range scripts {
				fmt.Println(script)
			}
		case "help":
			fmt.Println(HELP_INFO)
		case "clear":
			cmd := exec.Command("clear")
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			if err := cmd.Run(); err != nil {
				fmt.Println("清屏失败:", err)
			}
		case "exit", "quit":
			fmt.Println("等待所有脚本结束，退出 ScriptManager。")
			sm.Wait()
			return
		default:
			fmt.Println("未知命令:", args[0])
		}
	}
}
